package com.example.androidproject.movie.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.androidproject.R;
import com.example.androidproject.base.BaseFragment;
import com.example.androidproject.movie.activity.MovieDetailActivity;
import com.example.androidproject.movie.adapter.MovieAdapter;
import com.example.androidproject.movie.adapter.MovieRecyclerViewAdapter;
import com.example.androidproject.movie.bean.ResultBeanData;
import com.example.androidproject.utils.GlobalFunction;
import com.example.androidproject.utils.GlobalVariable;
import com.example.androidproject.utils.RequestConstant;
import com.example.androidproject.utils.RequestParameters;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MovieFragment extends BaseFragment {
    private static final String TAG = "GGSTUDY";
    private static TextView nav_tv;
    //    private static ImageButton ib_top;
    private static RecyclerView rv_movie;
    private static TextView login_tv;
    private static OkHttpClient okHttpClient;
    private static MovieRecyclerViewAdapter adapter;
    private static ListView gv_movie_body;
    //    private static NestedScrollView sv_movie_body;
    private static boolean isLoading = false;
    private static LinearLayout ll_contentLoding;
    private static MovieAdapter movieBodyAdapter;


    //
    private static int bodyLimit = RequestParameters.LIMIT;
    private static int bodyPage = RequestParameters.PAGE;
    static ArrayList<ResultBeanData.DataBean> dataList = new ArrayList<>();

    @Override
    public View initView() {
        Log.e(TAG, "主页视图被初始化了");
        View view = View.inflate(mContext, R.layout.fragment_movie, null);
//        nav_tv = view.findViewById(R.id.nav_tv);
//        ib_top = view.findViewById(R.id.ib_top);
        rv_movie = view.findViewById(R.id.rv_movie);
//        login_tv = view.findViewById(R.id.login_tv);
        gv_movie_body = view.findViewById(R.id.gv_movie_body);
//        sv_movie_body = view.findViewById(R.id.sv_movie_body);
        ll_contentLoding = view.findViewById(R.id.ll_contentLoding);

        okHttpClient = new OkHttpClient();
        initListener();

        return view;
    }

    private void initListener() {
        // 设置nav点击事件监听
//        setNavClickListener(nav_tv, login_tv);
    }

    @Override
    public void initData() {
        super.initData();
        getBannerDataFromNet();
        getBodyDataFromNet();
    }

    /**
     * 获取Banner横幅条的数据
     */
    private void getBannerDataFromNet() {
        String classify = RequestParameters.CLASSIFY;
//        RequestParameters.LIMIT = "3";
        int limit = 3;
        int page = RequestParameters.PAGE;
        String url = RequestConstant.MOVIE_IMG_URL + "?" + "classify=" + classify + "&limit=" + limit + "&page=" + page;
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 失败
                Log.d(TAG, "onFailure: " + e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                // 成功
                if (response.isSuccessful()) {
                    /**
                     *  OkHttp请求回调中response.body().string()只能有效调用一次
                     * 调用response.body().string()时数据流已关闭，再次调用提示已closed。
                     * 把代码修改完为只调用一次response.body().string()即可
                     */
                    //Log.e(TAG, "onResponse: " + response.body().string());
                    processData(response.body().string(), 1);
                } else {
//                    GlobalFunction.netWorkDisconnection_hideDialog(mContext, response);
                }
            }
        });
    }

    /**
     * 获取Body主体内容数据
     */
    private static void getBodyDataFromNet() {
        isLoading = true;
        String classify = RequestParameters.CLASSIFY;
        String url = RequestConstant.MOVIE_IMG_URL + "?" + "classify=" + classify + "&limit=" + bodyLimit + "&page=" + bodyPage;
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                // 成功
                if (response.isSuccessful()) {
                    Message mes = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("visible", "visible");
                    mes.setData(bundle);
//                    GlobalFunction.dialogVisibilityHandler.sendMessage(new Message());
                    dialogVisibilityHandler.sendMessage(new Message());
                    isLoading = false;
                    processData(response.body().string(), 2);
                } else {
                    dialogGONEHandler.sendMessage(new Message());
//                    GlobalFunction.netWorkDisconnection_hideDialog(mContext, response);
                }
            }
        });
    }

    private static void processData(String json, int flag) {
        Gson gson = new Gson();
        ResultBeanData resultBeanData = gson.fromJson(json, ResultBeanData.class);
        ArrayList<ResultBeanData.DataBean> data = (ArrayList<ResultBeanData.DataBean>) resultBeanData.getData();

        if (resultBeanData.getStatus() == 0) {
//            Log.d(TAG, "processData: 请求成功->" + resultBeanData.getStatus());
            if (data != null) {
                Message msg = new Message();
                Bundle Bundle = new Bundle();
                Bundle.putParcelableArrayList("data", data);
                Bundle.putInt("total", resultBeanData.getTotal());
                msg.setData(Bundle);
                if (flag == 1) {
                    Bundle.putParcelableArrayList("data", data);
                    // Banner
                    bannerhandler.sendMessage(msg);
                } else if (flag == 2) {
                    // Body
//                    dataList.addAll(data);
                    movieBodyHandler.sendMessage(msg);
                }
            } else {
                // 没有数据
                Toast.makeText(mContext, "没有数据", Toast.LENGTH_SHORT).show();
            }
        } else {
            Log.d(TAG, "processData: 请求失败->" + resultBeanData.getStatus());
//            Toast.makeText(mContext, "网络请求有误，请检查", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * // 处理 提示框的隐藏
     */
    @SuppressLint("HandlerLeak")
    public static final Handler dialogGONEHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            ll_contentLoding.setVisibility(View.GONE);
        }
    };
    /**
     * // 处理 提示框的显示
     */
    @SuppressLint("HandlerLeak")
    public static final Handler dialogVisibilityHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            ll_contentLoding.setVisibility(View.VISIBLE);
        }
    };
    // 创建Handler 更新UI
    @SuppressLint("HandlerLeak")
    private static final Handler bannerhandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            ArrayList<ResultBeanData.DataBean> data = msg.getData().getParcelableArrayList("data");
            rv_movie.setLayoutManager(new GridLayoutManager(mContext, 1));
            adapter = new MovieRecyclerViewAdapter(mContext, data, 1);
            rv_movie.setAdapter(adapter);
        }
    };

    // 处理 数据的显示
    @SuppressLint("HandlerLeak")
    public static final Handler movieBodyHandler = new Handler(Looper.getMainLooper()) {
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            ArrayList<ResultBeanData.DataBean> data = msg.getData().getParcelableArrayList("data");
            int total = msg.getData().getInt("total");
            //movieBodyAdapter = new MovieBodyAdapter(mContext, dataList);
//            ll_contentLoding.setVisibility(View.GONE);
//            GlobalFunction.dialogGONEHandler.sendMessage(new Message());
            dialogGONEHandler.sendMessage(new Message());
//            dataList.addAll(data);
            /**
             * 解决 listView或者是gridview底部加载 回到顶部的问题
             */
            if (movieBodyAdapter == null) {
                movieBodyAdapter = new MovieAdapter(mContext, dataList);
                gv_movie_body.setAdapter(movieBodyAdapter);
                movieBodyAdapter.refresh(data);
            } else {
                movieBodyAdapter.refresh(data);

//                movieBodyAdapter.notifyDataSetChanged();
            }
            // 使用自定义adapter 来实现 listview向gridview转换 gridview性能不够好，很多也不方便
//            gv_movie_body.setFocusable(false);
            movieBodyAdapter.setNumColumns(3);
            // 滑动监听
            gv_movie_body.setOnScrollListener(new AbsListView.OnScrollListener() {
                private int lastVisiblePositionY = 0;
                private int getLastVisiblePosition = 0;
                private int y;

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                        //滚动到底部
                        if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                            View v = (View) view.getChildAt(view.getChildCount() - 1);
                            int[] location = new int[2];
                            v.getLocationOnScreen(location); //获取在整个屏幕内的绝对坐标
                            y = location[1];
                            if (view.getLastVisiblePosition() != getLastVisiblePosition && lastVisiblePositionY != y) {
                                //第一次拖至底部
                                getLastVisiblePosition = view.getLastVisiblePosition();
                                lastVisiblePositionY = y;
                                if (isLoading) {
                                    return;
                                }
                                if (bodyLimit * bodyPage >= total) {
                                    Toast.makeText(mContext, "数据已经加载完了", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                bodyPage += 1;
                                getBodyDataFromNet();
                                return;
                            } else if (view.getLastVisiblePosition() == getLastVisiblePosition && lastVisiblePositionY == y) {
                                //第二次拖至底部
                            }
                        }

                        //未滚动到底部，第二次拖至底部都初始化
                        getLastVisiblePosition = 0;
                        lastVisiblePositionY = 0;
                    }
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                }
            });

        }
    };
    /**
     * // item 点击 监听
     * 这里我用的listview 变成了gridview 来显示内容 所以用setOnItemClickListener 是不行的，
     * 因为position 是listview的 无法实现点击每一个内容都跳转
     * 所以 这里的点击事件 要到 movieadapter里面去实现
     */
    @SuppressLint("HandlerLeak")
    public static Handler PostionHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            int position = msg.getData().getInt("position");
//            Log.d(TAG, "handleMessage: 11:" + position);
            // 跳转到电影详情页面
            Intent intent = new Intent(mContext, MovieDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putParcelable("data", dataList.get(position));
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        movieBodyAdapter = null;
    }
}
